package com.aurora.app.service;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.aurora.app.dao.ChatGroupDao;
import com.aurora.app.entity.ChatGroup;
import com.aurora.app.entity.Help;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingStory;
import com.aurora.app.entity.User;
import com.aurora.app.enums.UtTsType;
import com.aurora.base.dao.BaseDao;
import com.aurora.base.service.BaseService;

@Service
public class ChatGroupService extends BaseService<ChatGroup> {

	@Resource
	private ChatGroupDao baseDao;

	@Override
	public BaseDao<ChatGroup> getBaseDao() {
		// TODO Auto-generated method stub
		return this.baseDao;
	}

	/**
	 * 寻找一个聊天组，没有就新建一个返回
	 * 
	 * @param thing
	 * @param user
	 * @param utTsType
	 * @return
	 */
	@Transactional
	public ChatGroup getChatGroup(Thing thing, ThingStory thingStory, Help help, User user, UtTsType utTsType) {

		ChatGroup cg = null;
		switch (utTsType) {
		case UserThing:
			cg = this.baseDao.find("o.thing = ? and o.user = ? and o.isDelete = 0", thing, user);
			if (cg == null) {
				cg = new ChatGroup();
				cg.setThing(thing);
				cg.setUser(user);
				cg.setUtTsType(utTsType);
				this.baseDao.persist(cg);
				return cg;
			}
			break;
		case ThingStory:
			cg = this.baseDao.find("o.thingStory = ? and o.user = ? and o.isDelete = 0", thingStory, user);
			if (cg == null) {
				cg = new ChatGroup();
				cg.setThingStory(thingStory);
				cg.setUser(user);
				cg.setUtTsType(utTsType);
				this.baseDao.persist(cg);
				return cg;
			}
			break;
		case Help:
			cg = this.baseDao.find("o.help = ? and o.user = ? and o.isDelete = 0", help, user);
			if (cg == null) {
				cg = new ChatGroup();
				cg.setHelp(help);
				cg.setUser(user);
				cg.setUtTsType(utTsType);
				this.baseDao.persist(cg);
				return cg;
			}
			break;
		}
		return cg;
	}

	public List<ChatGroup> getListByThing(Thing thing) {
		return this.baseDao.list("o.thing = ? and o.isDelete = 0 ", thing);
	}

}
